package com.mysiteforme.admin.controller.scrap;

import com.xiaoleilu.hutool.date.DateUtil;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mysiteforme.admin.entity.ScrapList;
import com.mysiteforme.admin.entity.scrapVO.Stage;
import com.mysiteforme.admin.util.other.LayerData;
import com.mysiteforme.admin.util.other.RestResponse;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.annotation.SysLog;
import com.mysiteforme.admin.base.BaseController;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
 * <p>
 * 报废数据  前端控制器
 * </p>
 */
@Controller
@RequestMapping("/admin/scrap")
public class ScrapController extends BaseController {
	private static final Logger LOGGER = LoggerFactory.getLogger(ScrapController.class);
    @GetMapping("list")
    @SysLog("跳转报废数据列表")
    public String list(){
        return "/admin/scrap/list";
    }
    @RequiresPermissions("scrap:list")
    @PostMapping("list")
    @ResponseBody
    @SysLog("请求报废数据列表数据")
    public LayerData<ScrapList> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                      @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                      ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        LayerData<ScrapList> layerData = new LayerData<>();
        EntityWrapper<ScrapList> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag",false);
        if(!map.isEmpty()){
            String soNumber = (String) map.get("soNumber");
            if(StringUtils.isNotBlank(soNumber)) {
                wrapper.like("so_number",soNumber);
            }else{
                map.remove("soNumber");
            }

            String woNumber = (String) map.get("woNumber");
            if(StringUtils.isNotBlank(woNumber)) {
                wrapper.like("wo_number",woNumber);
            }else{
                map.remove("woNumber");
            }

            String process = (String) map.get("process");
            if(StringUtils.isNotBlank(process)) {
                wrapper.like("process",process);
            }else{
                map.remove("process");
            }

            String scrapProject = (String) map.get("scrapProject");
            if(StringUtils.isNotBlank(scrapProject)) {
                wrapper.like("scrap_project",scrapProject);
            }else{
                map.remove("scrapProject");
            }

            String beginScrapDate = (String) map.get("beginScrapDate");
            String endScrapDate = (String) map.get("endScrapDate");
            if(StringUtils.isNotBlank(beginScrapDate)) {
                Date begin = DateUtil.parse(beginScrapDate);
                wrapper.ge("scrap_date",begin);
            }else{
                map.remove("beginScrapDate");
            }
            if(StringUtils.isNotBlank(endScrapDate)) {
                Date end = DateUtil.parse(endScrapDate);
                wrapper.le("scrap_date",end);
            }else{
                map.remove("endScrapDate");
            }

        }
        wrapper.orderBy("scrap_date", false);
        Page<ScrapList> pageData = scrapService.selectPage(new Page<>(page,limit),wrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    @GetMapping("add")
    @SysLog("跳转新增报废数据页面")
    public String add(){
        return "/admin/scrap/add";
    }
    
    @RequiresPermissions("scrap:add")
    @PostMapping("add")
    @SysLog("保存新增报废数据数据")
    @ResponseBody
    public RestResponse add(ScrapList scrap){
        if(StringUtils.isBlank(scrap.getProcess())){
            return RestResponse.failure("改善项目不能为空");
        }
        if(StringUtils.isBlank(scrap.getScrapProject())){
            return RestResponse.failure("报废项目不能为空");
        }
        scrapService.insert(scrap);
        return RestResponse.success();
    }
    
    @GetMapping("edit")
    @SysLog("跳转编辑报废数据页面")
    public String edit(Long id,Model model){
    	ScrapList scraplist = scrapService.selectById(id);
        model.addAttribute("scrap",scraplist);
        return "/admin/scrap/edit";
    }
    
    @RequiresPermissions("scrap:edit")
    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑报废数据数据")
    public RestResponse edit(ScrapList scrapList){
        if(null == scrapList.getId() || 0 == scrapList.getId()){
            return RestResponse.failure("ID不能为空");
        }
        if(StringUtils.isBlank(scrapList.getProcess())){
            return RestResponse.failure("改善项目不能为空");
        }
        if(StringUtils.isBlank(scrapList.getScrapProject())){
            return RestResponse.failure("报废项目不能为空");
        }
        scrapService.updateById(scrapList);
        return RestResponse.success();
    }
    
    @RequiresPermissions("scrap:delete")
    @PostMapping("delete")
    @ResponseBody
    @SysLog("删除报废数据数据")
    public RestResponse delete(@RequestParam(value = "id",required = false)Long id){
        if(null == id || 0 == id){
            return RestResponse.failure("ID不能为空");
        }
        ScrapList scrapList = scrapService.selectById(id);
        scrapList.setDelFlag(true);
        scrapService.updateById(scrapList);
        return RestResponse.success();
    }

    @RequiresPermissions("scrap:excel")
    @PostMapping("uploadExcel")
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)
    @ResponseBody
    @SysLog("Excel文件上传")
    public RestResponse uploadExcelFile(@RequestParam("excel") MultipartFile filename,HttpServletRequest httpServletRequest) {
		  try {
           	HSSFWorkbook wk = new HSSFWorkbook(filename.getInputStream());

     	        HSSFSheet sheet = wk.getSheetAt(0);
     		    if(sheet.getLastRowNum() <= 0){
     	              return RestResponse.failure("文件内容为空");
     		    }   		
     		       for(int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++){
     			          HSSFRow row = sheet.getRow(rowIndex);
     			         ScrapList scrapList = new ScrapList();
     			         if(row.getCell(0) != null) {
     			        	 scrapList.setQuantity((int)row.getCell(0).getNumericCellValue());
  			         }
     			        scrapList.setSoNumber(row.getCell(1).getStringCellValue());
     			        scrapList.setWoNumber(row.getCell(2).getStringCellValue());
     			        scrapList.setProcess(row.getCell(3).getStringCellValue());
     			        scrapList.setScrapProject(row.getCell(4).getStringCellValue());
     			        scrapList.setRemarks(row.getCell(5).getStringCellValue());
      			      if(row.getCell(6) != null) {
      			    	  scrapList.setStation((int)row.getCell(6).getNumericCellValue());
     			         }
      			      if(row.getCell(7) != null) {
      			    	 scrapList.setScrapDate(row.getCell(7).getDateCellValue());
     			         }
     			         boolean b= scrapService.insert( scrapList);
     				      if(b==false){
     				    	 return RestResponse.failure("第"+rowIndex +"行导入失败");
     				      }
     		        }               	     	    
             } catch (Exception e){
                 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                 LOGGER.error(e.getMessage());
                 System.out.println(e.getMessage());
                  return RestResponse.failure(e.getMessage());     
              }
              return RestResponse.success();
    }
    @RequiresPermissions("scrap:report")   
    @GetMapping("report")
    @SysLog("数据报告列表")
    public String report(){
        return "/admin/scrap/report";
    }
    
	@PostMapping("report")
    @ResponseBody
    @SysLog("请求报废数据报告")
    public LayerData<Stage> reports(@RequestParam(value = "page",defaultValue = "1")int page,@RequestParam(value = "limit",defaultValue = "10")int limit,ServletRequest request){
           Map map = WebUtils.getParametersStartingWith(request, "s_");
           LayerData<Stage> layerData = new LayerData<>();
           Map<Object, Object> queryMap = new HashMap<Object, Object>();
           String beginScrapDate = (String) map.get("beginScrapDate");
           String endScrapDate = (String) map.get("endScrapDate");
           if(StringUtils.isNotBlank(beginScrapDate)) {
               Date begin = DateUtil.parse(beginScrapDate);
          	   queryMap.put("start_time",begin );
           }else{
               Date begin = DateUtil.parse(dateWeek.monday());
          	   queryMap.put("start_time",begin );
           }
           if(StringUtils.isNotBlank(endScrapDate)) {
               Date end = DateUtil.parse(endScrapDate);
          	   queryMap.put("end_time",end );
           }else{
               Date end = DateUtil.parse(dateWeek.sunday());
          	   queryMap.put("end_time",end );
           }
           
           String process = (String) map.get("process");
           if(StringUtils.isNotBlank(process)) {
        	   queryMap.put("process",process);
           }else{
               map.remove("process");
           }
           
      	   queryMap.put("start",(page - 1) * limit);
    	   queryMap.put("limit",limit);

    	   layerData.setData(stageService.ScrapStage(queryMap));
    	   layerData.setCount(stageService.ScrapStageGetTotal(queryMap));
		   return layerData ;
    }


	
}